package boardgamer.common.client;


import android.graphics.Canvas;
import android.graphics.RectF;
import android.view.MotionEvent;
import boardgamer.common.client.layout.LayoutGroup;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Simple button with a down animation. The down animation is a {@link Drawable} that is drawn
 * on top of the base button.
 */
public class ClickableButton implements Button {

  private final Drawable upButton;
  private final Drawable downDrawable;
  private final LayoutGroup drawables;

  private final HasEventHandler innerButton;

  private boolean touchDown = false;
  private boolean touchPressed = false;

  public ClickableButton(Button upButton, Display downDrawable) {
    this.upButton = checkNotNull(upButton, "upButton");
    this.downDrawable = checkNotNull(downDrawable, "downDrawable");

    this.innerButton = checkNotNull(upButton, "upButton");

    this.drawables = new LayoutGroup()
        .add(upButton).atCurrentRect()
        .add(downDrawable).atCurrentRect();
  }

  @Override
  public void handleEvent(float touchX, float touchY, int eventAction) {
    RectF collisionBox = innerButton.getCollisionBox();
    innerButton.handleEvent(touchX, touchY, eventAction);
    switch (eventAction) {
      case MotionEvent.ACTION_DOWN:
        if (collisionBox.contains(touchX, touchY)) {
          touchDown = true;
          touchPressed = true;
        }
        break;
      case MotionEvent.ACTION_MOVE:
        if (collisionBox.contains(touchX, touchY)) {
          if (touchDown) {
            touchPressed = true;
          }
        } else {
          touchPressed = false;
        }
        break;
      case MotionEvent.ACTION_UP:
        touchDown = false;
        touchPressed = false;
        break;
    }
  }

  @Override
  public RectF getCollisionBox() {
    return innerButton.getCollisionBox();
  }

  @Override
  public void draw(Canvas canvas) {
    upButton.draw(canvas);
    if (touchPressed) {
      downDrawable.draw(canvas);
    }
  }

  @Override
  public void setBoundingRect(RectF boundingRect) {
    this.drawables.setBoundingRect(boundingRect);
  }

  @Override
  public RectF getBoundingRect() {
    return new RectF(drawables.getBoundingRect());
  }
}
